﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace MyTcpIp.helper
{
    public class SerializeHelper
    {
        /// <summary>
        /// 字符串序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Data"></param>
        /// <returns></returns>
        public byte[] SerializeString<T>(T Data)
        {
            char[] chr = (Data as string).ToCharArray();

            byte[] bt = new byte[chr.Length];
            for (int i = 0; i < chr.Length; i++)
            {
                bt[i] = Convert.ToByte(chr[i]);
            }
            return bt;
        }
        /// <summary>
        /// 字符串反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Data"></param>
        /// <returns></returns>
        public T DeSerializeString<T>(byte[] Data)
        {
            string a = "";
            //for (int i = 0; i < Data.Length; i++)
            //{
            //    char c = Convert.ToChar(Data[i]);
            //    a = a + c.ToString();
            //}
            char[] s = Encoding.UTF8.GetChars(Data); 
            a = new string(s);
            object obj = a;
            return (T)obj;
        }
        /// <summary>
        /// 数据包序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Data"></param>
        /// <returns></returns>
        public byte[] Serialize<T>(T Data)
        {
            //得到结构体的大小
            int size = Marshal.SizeOf(Data);
            //创建byte数组
            byte[] bytes = new byte[size];
            //分配结构体大小的内存空间
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            //将结构体拷到分配好的内存空间
            Marshal.StructureToPtr(Data, structPtr, false);
            //从内存空间拷到byte数组
            Marshal.Copy(structPtr, bytes, 0, size);
            //释放内存空间
            Marshal.FreeHGlobal(structPtr);
            //返回byte数组
            return bytes;
        }
        
            /// <summary>
            /// 数据包反序列化
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="Data"></param>
            /// <returns></returns>
        public T DeSerialize<T>(byte[] Data)
        {
            //得到结构体的大小
            int size = Marshal.SizeOf(typeof(T));
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            //将byte数组拷到分配好的内存空间
            Marshal.Copy(Data, 0, structPtr, size);
            //将内存空间转换为目标结构体
            object obj = Marshal.PtrToStructure(structPtr, typeof(T));
            //释放内存空间
            Marshal.FreeHGlobal(structPtr);
            //返回结构体
            return (T)obj;
        }
    }
}
